package com.my.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.admin.entity.Tag;
import com.my.admin.service.TagService;
import com.my.admin.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
public class TagController {

    @Autowired
    private TagService service;

    @PostMapping("tag/get")
    public Rest tags(@RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize, @RequestBody Tag tag) {
        return Rest.ok().setData("page", service.page(new Page<>(pageNo, pageSize), new QueryWrapper<Tag>().
                like(StrUtil.isNotBlank(tag.getName()), "name", tag.getName()).like(StrUtil.isNotBlank(tag.getTagDesc()), "tag_desc", tag.getTagDesc())));
    }

    @PostMapping("tags")
    public Rest add(@RequestBody Tag tag) {
        if(service.save(tag)) {
            return Rest.ok("添加成功！");
        }else {
            return Rest.err("添加失败!");
        }
    }

    @PutMapping("tags")
    public Rest edit(@RequestBody Tag tag) {
        if(service.updateById(tag)) {
            return Rest.ok("修改成功！");
        }else {
            return Rest.err("修改失败！");
        }
    }

    @DeleteMapping("tags")
    public Rest del(@RequestParam long id) {
        if(service.removeById(id)) {
            return Rest.ok("删除成功！");
        }else {
            return Rest.err("删除失败！");
        }
    }

    @GetMapping("tag/repeat")
    public Rest repeat(@RequestParam String name, @RequestParam(defaultValue = "-1") Long id) {
        QueryWrapper<Tag> qw = new QueryWrapper<Tag>().eq("name", name);
        if(id != -1) {
            qw.ne("id", id);
        }
        return Rest.ok().setData("flag", service.getOne(qw) != null);
    }

    @GetMapping("tag/list")
    public Rest list() {
        return Rest.ok().setData("list", service.list());
    }

}
